<?php
/**
 * Created by PhpStorm.
 * User: huliren<huliren0516@163.com>
 * Date: 2017/9/8
 * Time: 15:15
 */
require('../../../common.inc.php');

define('SITE_AUTH', 'advertising-line-Ecommerce');

use lib\core\AdminAction;
use Act\EcommerceImg as Model;
use Common\Upload;
use Common\ResourcePathManager;
use Temai\CateItem;
use Temai\CustomItem;
use Temai\JuItem;
use Temai\NineItem;
use Temai\TqgItem;
use Temai\TqgTime;

class Ecommerce extends AdminAction
{
    private $list_url = 'data/modules/share/Ecommerce.php';
    private $itemtype = [
        0 => '自定义商品',
        1 => '分类商品',
        2 => '特抢购',
        3 => '特卖9块9包邮',
        4 => '聚划算商品'
    ];

    public function doDefault()
    {
        $smarty = $this->app->page();
        $where = ['Id >= ' => 0];


        $page = $_GET['page'] < 1 ? 1 : (int)$_GET['page'];
        $limit = parent::PAGE_SIZE;
        $offset = ($page - 1) * $limit;

        $info = Model::getList($where, $offset, $limit);
        $count = $info['count'];
        if ($count > 0) {
            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;

            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('page_info', $page_info);
            $smarty->value('pagination', $pagination);
            $smarty->value('list', $info['data']);
        }
        $smarty->output('share/Ecommerce_list.tpl');
    }

    public function doEdit()
    {
        $smarty = $this->app->page();
        $id = intval(trim($_GET['id']));

        $Scheme = loadconf('share/ecommerce');

        if ($id < 0) {
            HDshowMsg('数据不存在！', ['type' => 'error', 'url' => $this->list_url]);
        }
        if (!empty($id)) {
            $data = Model::getInfoByIds($id);
            if (empty($data)) {
                HDshowMsg('数据不存在！', ['type' => 'error', 'url' => $this->list_url]);
            }
            $smarty->value('info', $data);
        }
        $smarty->value('scheme', $Scheme);
        $smarty->output('share/Ecommerce_edit.tpl');
    }

    public function doUpdata()
    {
        $id = (isset($_POST['id']) and $_POST['id'] !== '') ? $_POST['id'] : null;
        $title = (isset($_POST['title']) and $_POST['title'] !== '') ? trim($_POST['title']) : null;
        $description = (isset($_POST['description']) and $_POST['description'] !== '') ? trim($_POST['description']) : null;
        $icon = $_FILES['icon'];
        //        $url = (isset($_POST['url']) and $_POST['url'] !== '') ? trim($_POST['url']) : null;
        $img = $_FILES['img'];
        $clickurl = (isset($_POST['imgurl']) and $_POST['imgurl'] !== '') ? trim($_POST['imgurl']) : null;
        $img2 = $_FILES['img2'];
        $clickurl2 = (isset($_POST['imgurl2']) and $_POST['imgurl2'] !== '') ? trim($_POST['imgurl2']) : null;
        $starttime = (isset($_POST['start_time']) and $_POST['start_time'] !== '') ? $_POST['start_time'] : null;
        $endtime = (isset($_POST['end_time']) and $_POST['end_time'] !== '') ? $_POST['end_time'] : null;

        $rel = false;

        if ($id !== null) {
            $info = [
                Model::FIELD_TITLE => $title,
                Model::FIELD_DESC => $description,
                //                Model::FIELD_URL =>$url,
                Model::FIELD_CLICK_URL => $clickurl,
                Model::FIELD_CLICK_URL2 => $clickurl2,
                Model::FIELD_START_TIME => $starttime,
                Model::FIELD_END_TIME => $endtime,
            ];
            $iconUrlAddre = "";
            if (isset($icon['name']) && $icon['error'] == 0 && $icon['size'] > 0) {
                // 复制图片
                $iconUrlAddre = Upload::saveFile($icon['tmp_name'], ResourcePathManager::getEcommerceConfigSavePath());
                $info = array_merge($info, [Model::FIELD_ICON => $iconUrlAddre]);
            }

            $imgUrlAddre = "";
            if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0) {
                // 复制图片
                $imgUrlAddre = Upload::saveFile($img['tmp_name'], ResourcePathManager::getEcommerceConfigSavePath());
                $info = array_merge($info, [Model::FIELD_IMG_URL => $imgUrlAddre]);
            }

            $imgUrlAddre2 = "";
            if (isset($img2['name']) && $img2['error'] == 0 && $img2['size'] > 0) {
                // 复制图片
                $imgUrlAddre2 = Upload::saveFile($img2['tmp_name'], ResourcePathManager::getEcommerceConfigSavePath());
                $info = array_merge($info, [Model::FIELD_IMG_URL2 => $imgUrlAddre2]);
            }

            $rel = Model::update($id, $info);
        } else {
            $iconUrlAddre = "";
            if (isset($icon['name']) && $icon['error'] == 0 && $icon['size'] > 0) {
                // 复制图片
                $iconUrlAddre = Upload::saveFile($icon['tmp_name'], ResourcePathManager::getEcommerceConfigSavePath());
            } else {
                HDshowMsg('icon图片上传失败！', ['type' => 'error', 'url' => $this->list_url]);
            }

            $imgUrlAddre = "";
            if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0) {
                // 复制图片
                $imgUrlAddre = Upload::saveFile($img['tmp_name'], ResourcePathManager::getEcommerceConfigSavePath());
            } else {
                HDshowMsg('img图片上传失败！', ['type' => 'error', 'url' => $this->list_url]);
            }

            $imgUrlAddre2 = "";
            if (isset($img2['name']) && $img2['error'] == 0 && $img2['size'] > 0) {
                // 复制图片
                $imgUrlAddre2 = Upload::saveFile($img2['tmp_name'], ResourcePathManager::getEcommerceConfigSavePath());
            }

            $info = [
                Model::FIELD_TITLE => $title,
                Model::FIELD_DESC => $description,
                Model::FIELD_ICON => $iconUrlAddre,
                //                Model::FIELD_URL =>$url,
                Model::FIELD_IMG_URL => $imgUrlAddre,
                Model::FIELD_CLICK_URL => $clickurl,
                Model::FIELD_IMG_URL2 => $imgUrlAddre2,
                Model::FIELD_CLICK_URL2 => $clickurl2,
                Model::FIELD_START_TIME => $starttime,
                Model::FIELD_END_TIME => $endtime,
            ];
            $rel = Model::add($info);
        }

        if ($rel) {
            HDshowMsg('保存成功', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('操作失败', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    public function doDelete()
    {
        $id = $_GET['id'];
        $rel = Model::delete($id);
        if ($rel) {
            HDshowMsg('删除成功', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('操作失败', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    public function doSelectItemsType()
    {
        $smarty = $this->app->page();
        $urltype = $_GET['urltype'];

        $smarty->value('itemtype', $this->itemtype);
        $smarty->value('urltype', $urltype);
        $smarty->output('share/Items.tpl');
    }

    public function doSearchItem()
    {
        $itemtype = $_GET['itemtype'];
        $page = $_GET['page'] < 1 ? 1 : (int)$_GET['page'];
        $limit =parent::PAGE_SIZE;
        $offset = ($page - 1) * $limit;
        $rel = false;

        switch ($itemtype) {
            case 0:
                $customitem = new CustomItem();
                $count = $customitem->total([]);
                $rel = $customitem->find([], [
                    'limit' => $limit,
                    'skip' => $offset,
                    'sort' => [$customitem::FIELD_CRATE_TIME => -1]
                ]);
                foreach ($rel as $k => $v){
                    $rel[$k]['ReservePrice'] = formatItemPrice($v['ReservePrice']);
                    $rel[$k]['ZkFinalPrice'] = formatItemPrice($v['ZkFinalPrice']);
                }
                break;
            case 1:
                $cateitem = new CateItem();
                $count = $cateitem->total([]);
                $rel = $cateitem->find([], [
                    'limit' => $limit,
                    'skip' => $offset,
                    'sort' => [$cateitem::FIELD_CREATE_TIME => -1]
                ]);
                foreach ($rel as $k => $v){
                    $rel[$k]['ReservePrice'] = formatItemPrice($v['ReservePrice']);
                    $rel[$k]['ZkFinalPrice'] = formatItemPrice($v['ZkFinalPrice']);
                }
                break;
            case 2:
                $tagtime = new TqgTime();
                $times = $tagtime->getTqgTimeList();
                $time = $times[0]['Time'];
                $info = $this->pageQuery($time,$offset,$limit);
                $count = $info['Total'];
                $rel = $info['List'];
                foreach ($rel as $k => $v){
                    $rel[$k]['ReservePrice'] = formatItemPrice($v['ReservePrice']);
                    $rel[$k]['ZkFinalPrice'] = formatItemPrice($v['ZkFinalPrice']);
                }

                break;
            case 3:
                $cateitem = new CateItem();
                $count = $cateitem->total(['ZkFinalPrice'=>['$lte'=>990]]);
                $rel = $cateitem->find(['ZkFinalPrice'=>['$lte'=>990]], [
                    'limit' => $limit,
                    'skip' => $offset,
                    'sort' => [$cateitem::FIELD_CREATE_TIME => -1]
                ]);
                foreach ($rel as $k => $v){
                    $rel[$k]['ReservePrice'] = formatItemPrice($v['ReservePrice']);
                    $rel[$k]['ZkFinalPrice'] = formatItemPrice($v['ZkFinalPrice']);
                }

                break;
            case 4:
                $juitem = new JuItem();
                $count = $juitem->total([]);
                $rel = $juitem->find([], [
                    'limit' => $limit,
                    'skip' => $offset,
                    'sort' => [$juitem::FIELD_CRATE_TIME => -1]
                ]);
                foreach ($rel as $k => $v){
                    $rel[$k]['OrigPrice'] = formatItemPrice($v['OrigPrice']);
                    $rel[$k]['ActPrice'] = formatItemPrice($v['ActPrice']);
                }

                break;
        }
        $pagination = $this->pagination($count, $limit, $page);
        if ($rel) {
            $this->output(['type' => 'yes', 'data' => $rel,'pagination'=>$pagination,'k'=>$itemtype]);
        } else {
            $this->output(['type' => 'no']);
        }
    }

    private function pageQuery($time, $offset = 0, $limit = 20)
    {
        $Modle = new TqgItem();
        $parseTime = $this->parseTime($time);

        $startTime = $parseTime . ':00:00';
        $endTime = $parseTime . ':59:59';
        $filter = [
            $Modle::FIELD_START_TIME => ['$gte' => $startTime, '$lte' => $endTime],
            $Modle::FIELD_END_TIME => ['$gte' => $endTime]
        ];

        $total = $Modle->total($filter);
        $rows = $Modle->find($filter, [
            'limit' => $limit,
            'skip' => $offset,
            'sort' => [$Modle::FIELD_SOLD_NUM => -1, $Modle::FIELD_CREATE_TIME => -1, $Modle::FIELD_START_TIME => 1]
        ]);

        return [
            'Total' => $total,
            'List' => $rows
        ];
    }


    /**
     * 解析时间
     *
     * @param $time
     * @return bool|array
     */
    private function parseTime($time)
    {
        if (strlen($time) == 10) {
            $year = substr($time, 0, 4);
            $month = substr($time, 4, 2);
            $day = substr($time, 6, 2);
            $hour = substr($time, 8, 2);

            return sprintf('%s-%s-%s %s', $year, $month, $day, $hour);
        }

        return false;
    }

}

$app->run();